package ar.edu.unlu.sistemas.p2p.business.net.tcp;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import ar.edu.unlu.sistemas.p2p.business.net.ProtocolListener;
import ar.edu.unlu.sistemas.p2p.business.util.Logger;


public class TCPListener extends Thread implements ProtocolListener {
	
	
		protected ServerSocket socket;

		public TCPListener(int port) throws IOException{
			try {
				Logger.logDebug(this.getClass().getName(),"Intenta abrir servidor en "+
						Inet4Address.getByName("localhost").getHostAddress()+":"+String.valueOf(port));
				//this.setSocket(new ServerSocket(port,10,Inet4Address.getByName("localhost")));
				this.setSocket(new ServerSocket(port));
				this.start();
			} catch (IOException ioe) {
				Logger.logError(this.getClass().getName(),"Error al iniciar conexion", ioe);
				throw ioe;
			}
		}

		public ServerSocket getSocket() {
			return socket;
		}

		public void setSocket(ServerSocket socket) {
			this.socket = socket;
		}
		
		public void run () {
			Socket s1;
			Logger.logInfo(this.getClass().getName(),this.getSocket().getLocalSocketAddress().toString()+" Comienza el loop para aceptar conexiones");
			try {
				while (true) {
					s1 = this.getSocket().accept();
					Logger.logInfo(this.getClass().getName(),"Acepta conexión de "+s1.getRemoteSocketAddress().toString());
					new PeerTCPConnection(s1);
				}
				
			} catch (SocketException se) {
				Logger.logError(this.getClass().getName(),"Error aceptando conexiones",se);
			} catch (IOException ioe) {
				Logger.logError(this.getClass().getName(),"Error I/O aceptando conexiones",ioe);
			}		
		}
		
		public void close(){
			try {
			this.getSocket().close();
			} catch (IOException ioe) {
				Logger.logError(this.getClass().getName(),"Error I/O al intentar cerrar la conexión",ioe);
			}
		}
		
}

